import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';

import { Layout, Input, Button, Tabs, Table, Menu, Dropdown, InputNumber, Popconfirm, Space, message } from 'antd';
import { DownOutlined } from '@ant-design/icons';

import TaskDetail from './components/taskDetail/taskDetail'

import './style.scss'

const { Content } = Layout;
const { TabPane } = Tabs;

class Task extends Component{
  state={
    key: '1',
    searchValue: '',
    page: 10,
    currentTaskId: undefined,
    currentTaskStatus: undefined,
  }

  componentDidMount(){
    let username = "admin";//待修改
    this.props.getHistoryTaskList(username);
  }

  setSearchValue = (e) => {
      this.setState({searchValue: e.target.value})
  }

  onTabsChange = (key) => {
    this.setState({key});
    if(key==="1"){
      let username = "admin";//待修改
      this.props.getHistoryTaskList(username)
      
    }else if(key === '2'){
      let username = "admin";//待修改
      this.props.getTaskList(username);
    }
  }

  // handleMenuClick = (e) => {
  //   let taskId = this.state.currentTaskId;
  //   let taskStatus = this.state.currentTaskStatus;
  //   if (e.key === '运行') {
  //     this.props.runTask(taskId);
  //   }else if(e.key === '暂停/重启'){
  //     this.props.pauseTask(taskId);
  //   }else if(e.key === '终止'){
  //     if(taskStatus === '未开始'){
  //       message.info('未开始的任务不能终止')
  //     }else{
  //       this.props.stopTask(taskId);
  //     }
  //   }
  //   this.setState({
  //     currentTaskId: undefined,
  //     currentTaskStatus: undefined,
  //   });
  // };

  changePage = (value) => {
    this.setState({page:value});
  }

  handleDetailClick = (taskId) => {
    this.props.getTaskInfo(taskId);
    this.detail.handleClick();
  }

  getColumns = () => {
    let columns = [
      {
        title:"序号",
        render:(text, record, index)=><span>{index+1}</span>,
       
      },{
        title:"服务编号", dataIndex:"taskIndex", key:"taskIndex", 
        render: (text, record) => <Link to={{pathname:'/dataCollection/taskLog', query: {record}}}>{text}</Link>
      },{
        title:"服务名称", dataIndex:"taskName", key:"taskName",
      },{
        title:"数据源名称", dataIndex:"sourceName", key:"sourceName",
      },{
        title:"采集周期", dataIndex:"taskTypeName", key:"taskTypeName", 
      },{
        title:"运行状态", dataIndex:"taskStatus", key:"taskStatus", 
      },{
        title: "服务描述",
      },
      {
        title:"创建时间", dataIndex:"createDate", key:"createDate", 
      },{  
        title:"操作", dataIndex:"operation", key:"operation",
        render: (text,record)=>(
          <Space>
            <a onClick={()=>this.handleDetailClick(record.taskId)}>查看</a>
            <TaskDetail onRef={ref=>this.detail=ref}/>
            <a >编辑</a>
            <Popconfirm
            title="确认删除?"
            onConfirm={() => this.props.deleteTask(record.taskId)}
            >
              <a >删除</a>
            </Popconfirm>
            {/* <Dropdown overlay={menu} trigger={['click']}>
              <a onClick={e => {e.preventDefault();this.setState({currentTaskId:record.taskId,currentTaskStatus:record.taskStatus});}}>
                更新状态<DownOutlined />
              </a>
            </Dropdown> */}
            {
              record.taskStatus !== '未开始' &&  <a onClick={()=>this.props.stopTask(record.taskId)}>取消发布</a>
            }
            {
              record.taskStatus === '未开始' &&  <a onClick={()=>this.props.runTask(record.taskId)}>发布</a>
            }
            { 
              // record.taskStatus !== '未开始' && 
                <Link to={{pathname:'/dataCollection/monitor', query: {record}}} >
                  监视
                </Link>
            }
          </Space>
        )
      }
    ]

    // columns.push()
    // this.state.key === '2' && columns.push({ // 历史任务
    //   title:"操作", dataIndex:"operation", key:"operation",
    //   render: (text,record)=>(
    //     <span>
    //       <Button type="link">查看</Button>
    //       <Button type="link" onClick={()=>this.props.getTaskLog(record.taskId)}>日志详情</Button>
    //     </span>
    //   )
    // })

    return columns;
  }

  getTotal = () => {
    const {key} = this.state;
    if(key === '1')  return this.props.historyTasks.length
    if(key === '2')  return this.props.tasks.length
    return 0
  }

  handleReset = ()=>{
    const {key} = this.state;
    this.setState({searchValue: ''})
    if(key==="1"){
      let username = "admin";//待修改
      this.props.getHistoryTaskList(username)
      
    }else if(key === '2'){
      let username = "admin";//待修改
      this.props.getTaskList(username);
    }
  }

  handleSearch = () =>{
    const {key, searchValue} = this.state;
    if(key==="1"){
      let username = "admin";//待修改
      this.props.getHistoryTaskListSearch(username, searchValue)
    }else if(key === '2'){
      let username = "admin";//待修改
      this.props.getTaskListSearch(username, searchValue);
    }
  }

  render(){
    const {page, key, searchValue} = this.state;
    return (
      <Content style={{marginTop:12}}>
        <div>
          <div style={{display: 'inline-block', fontWeight: 'bold'}}>数据采集任务列表</div>
          <div style={{float: 'right', display: 'inline-block', height:'100%'}}>
            <span>关键字: <Input placeholder="请输入服务名称/编号" style={{width: 200}} onChange={this.setSearchValue} value={searchValue}/></span>
            <Button type="primary" style={{marginLeft: 12}} onClick={this.handleSearch} disabled={!searchValue}>搜索</Button>
            <Button type="primary" style={{marginLeft: 12}} onClick={this.handleReset}>重置</Button>
            <Button type="primary" style={{marginLeft: 24}} href='#/dataCollection/taskCreate'>新建</Button>
            {/* <CreateTask/> */}
          </div>
        </div>
        <div className="table-box" style={{marginTop:12}}>
          <Tabs type="card" onChange={this.onTabsChange}>
            <TabPane tab="已发布任务" key="1" />
            <TabPane  tab="未发布任务" key="2" />
          </Tabs>
          <Table 
            pagination={{pageSize:page,showSizeChanger:false}} 
            dataSource={key === '1' ? this.props.historyTasks : this.props.tasks}
            columns={this.getColumns()}
          ></Table>
        <div className={this.getTotal()>0 ? 'footer' : 'withoutPagination'}>
          显示<InputNumber min={1} defaultValue={page} onChange={this.changePage}/>项结果，共{this.getTotal()}项
        </div>
      </div>
      </Content>
    );
  }
} 

const mapStateToProps = (state) => {
  return {
    tasks: state.getIn(['task','tasks']).toJS(),
    historyTasks: state.getIn(['task','historyTasks']).toJS(),
    taskLog: state.getIn(['tasks','taskLog']),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getTaskList(username){
    dispatch(actionCreators.getTaskListOperation(username));
  },
  getTaskListSearch(username, search){
    dispatch(actionCreators.getTaskListSearch(username, search));
  },
  runTask(taskId){
    dispatch(actionCreators.runTaskOperation(taskId));
  },
  deleteTask(taskId){
    dispatch(actionCreators.deleteTaskOperation(taskId));
  },
  pauseTask(taskId){
    dispatch(actionCreators.pauseTaskOperation(taskId));
  },
  stopTask(taskId){
    dispatch(actionCreators.stopTaskOperation(taskId));
  },
  getTaskInfo(taskId){
    dispatch(actionCreators.getTaskInfoOperation(taskId));
  },
  getHistoryTaskList(username){
    dispatch(actionCreators.getHistoryTaskListOperation(username));
  },
  getHistoryTaskListSearch(username, search){
    dispatch(actionCreators.getHistoryTaskListSearch(username, search));
  },
  getTaskLog(taskId){
    dispatch(actionCreators.getTaskLogOperation(taskId));
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Task);